﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ehost
{
    class Utils
    {
        /*
         * 简单是否符合ip的格式，没有判断有效性
         * */
        public static bool  isIp(String ipStr)
        {
            return Regex.IsMatch(ipStr, @"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$");    
        }


        /*
         * 将host的字符串转为Host类
         * */
        public static Host toHost(String hostStr)
        {
            if (hostStr == null || hostStr.Trim().Equals("")) return null;

            hostStr = hostStr.Trim();

            Host host = new Host();

           
            String[] array =hostStr.Split(new String[]{" "},3,StringSplitOptions.RemoveEmptyEntries);

            //127.0.0.1 www.baidu.com这种形式的
            if (array.Length >= 2)
            {
                if (array[0].Contains("#"))
                {
                    host.able = false;
                    host.ip = array[0].Substring(1, array[0].Length-1);

                    if (!isIp(host.ip))
                    {
                        return null;
                    }

                }
                else
                {
                    host.able = true;
                    host.ip = array[0];

                    if (!isIp(host.ip))
                    {
                        return null;
                    }

                }
                host.domain = array[1];
            }
            else
            {
                return null;
            }

            if (array.Length == 3)
            {
                host.comment = array[2].Substring(1);
            }
            return host;
        }
    }
}
